package com.manong.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manong.aspect.AutoFill;
import com.manong.entity.Shop;
import com.manong.entity.Sup;
import com.manong.service.ShopService;
import com.manong.utils.JwtUtils;
import com.manong.utils.Result;
import com.manong.vo.query.ShopVo;
import com.manong.vo.query.SupVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/api/shop")
public class ShopController {
    @Resource
    private ShopService shopService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private JwtUtils jwtUtils;

    /**
     * 查询采购单列表
     * @param shopVo
     * @return
     */
    @GetMapping("/list")
    public Result list(ShopVo shopVo){
        IPage<Shop> page = new Page<Shop>();
        page.setCurrent(shopVo.getPageNo());
        page.setSize(shopVo.getPageSize());
        shopService.findSupListByUsername(page,shopVo);
        return Result.ok(page);
    }

    @AutoFill(menu = "采购管理", type = "新建")
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:shop:add')")
    public Result add(@RequestBody Shop shop){
        shop.setShopTime(new Date());
        shop.setUsername(jwtUtils.getUsernameFromToken(request.getHeader("token")));
        if(shopService.save(shop)){
            return Result.ok().message("添加成功");
        }else{
            return Result.error().message("添加失败");
        }
    }

    @AutoFill(menu = "采购管理", type = "修改")
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:shop:edit')")
    public Result update(@RequestBody Shop shop){
        shop.setShopTime(new Date());
        shop.setUsername(jwtUtils.getUsernameFromToken(request.getHeader("token")));
        //调用修改方法
        if(shopService.updateById(shop)){
            return Result.ok().message("修改成功");
        }
        //返回数据
        return Result.error().message("修改失败");
    }

    @AutoFill(menu = "采购管理", type = "删除")
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:shop:delete')")
    public Result delete(@PathVariable Long id){
        if(shopService.deleteById(id)){
            return Result.ok().message("删除成功");
        }else{
            return Result.error().message("删除失败");
        }
    }

    @AutoFill(menu = "采购管理", type = "审核")
    @PutMapping("/audit")
    @PreAuthorize("hasAuthority('sys:shop:audit')")
    public Result audit(@RequestBody Shop shop){
        shop.setShopTime(new Date());
        //调用修改方法
        if(shopService.updateById(shop)){
            return Result.ok().message("修改成功");
        }
        //返回数据
        return Result.error().message("修改失败");
    }
}
